using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.Collections;

/// <summary>
/// 实现按钮跳动效果并处理场景跳转
/// </summary>
[RequireComponent(typeof(Button))]
public class BounceButton : MonoBehaviour
{
    [Header("跳动效果设置")]
    [Tooltip("最大缩放比例")]
    public float maxScale = 1.2f;
    [Tooltip("最小缩放比例")]
    public float minScale = 1.0f;
    [Tooltip("跳动动画持续时间")]
    public float bounceDuration = 0.5f;

    [Header("场景跳转设置")]
    [Tooltip("目标场景名称")]
    public string targetSceneName;

    private Button _button;
    private RectTransform _rectTransform;
    private Coroutine _bounceCoroutine;

    void Start()
    {
        // 获取组件引用
        _button = GetComponent<Button>();
        _rectTransform = GetComponent<RectTransform>();

        // 注册按钮点击事件
        _button.onClick.AddListener(OnButtonClick);

        // 开始跳动动画
        _bounceCoroutine = StartCoroutine(BounceAnimation());
    }

    /// <summary>
    /// 按钮跳动动画协程
    /// </summary>
    private IEnumerator BounceAnimation()
    {
        while (true)
        {
            // 从最小缩放到最大缩放
            yield return StartCoroutine(ScaleOverTime(minScale, maxScale, bounceDuration));
            // 从最大缩放到最小缩放
            yield return StartCoroutine(ScaleOverTime(maxScale, minScale, bounceDuration));
        }
    }

    /// <summary>
    /// 缩放动画协程
    /// </summary>
    /// <param name="startScale">开始缩放值</param>
    /// <param name="endScale">结束缩放值</param>
    /// <param name="duration">动画持续时间</param>
    private IEnumerator ScaleOverTime(float startScale, float endScale, float duration)
    {
        float elapsed = 0;
        while (elapsed < duration)
        {
            float t = elapsed / duration;
            // 使用平滑插值实现缓动效果
            float scale = Mathf.Lerp(startScale, endScale, Mathf.SmoothStep(0, 1, t));
            _rectTransform.localScale = new Vector3(scale, scale, 1);
            elapsed += Time.deltaTime;
            yield return null;
        }
        _rectTransform.localScale = new Vector3(endScale, endScale, 1);
    }

    /// <summary>
    /// 按钮点击事件处理
    /// </summary>
    private void OnButtonClick()
    {
        // 停止跳动动画
        if (_bounceCoroutine != null)
        {
            StopCoroutine(_bounceCoroutine);
        }

        // 恢复按钮原始大小
        _rectTransform.localScale = new Vector3(minScale, minScale, 1);

        // 跳转到目标场景
        if (!string.IsNullOrEmpty(targetSceneName))
        {
            SceneManager.LoadScene(targetSceneName);
        }
        else
        {
            Debug.LogError("目标场景名称未设置");
        }
    }

    void OnDestroy()
    {
        // 移除事件监听
        if (_button != null)
        {
            _button.onClick.RemoveListener(OnButtonClick);
        }
    }
}